package atlantik.ui;

import java.io.IOException;
import java.io.File;

import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Container;
import java.awt.Insets;

import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;

public class ConnectionDialog extends JFrame
{
	public String host;
	public int port;
	public String name;
	public int botCount;
	public boolean startAi;
	public boolean startLocalServer;

	private final JTextField hostEdit;
	private final JTextField portEdit;
	private final JTextField nameEdit;
	private final JComboBox botCountComboBox;

	private final JLabel hostLabel;
	private final JLabel portLabel;
	private final JLabel nameLabel;
	private final JLabel botCountLabel;
        private String tempHostName;

	final String botCountStrings[] = { "1", "2",  "3", "4", "5", "6", "7" };

	// ------------------------------------------------
	// Added by Jay S. on July 20
	/*
	 * tokenList (JComboBox) uses these additional files: images/gator.png
	 * etc...
	 */

	ImageIcon icon;
	private final JLabel tokenLabel;

	static final String[] tokenStrings =
	{ "albert", "basketball", "football", "helmet", "letter", "logo", "pail", "sofa" };
	JComboBox tokenList;
	private static String tokenName = "albert";
	// ------------------------------------------------

	private final JButton connectBtn;
	private final JCheckBox aiCheckBox;
	private final JCheckBox localServerCheckBox;

	private final JPanel mainpanel;

	public ConnectionDialog(String host, int port, String name,
			boolean startAi, boolean startLocalServer, int botCount)
	{
		super("Gatoropoly Connection Configuration");

		this.host = host;
		this.port = port;
		this.name = name;
		this.startAi = startAi;
		this.startLocalServer = startLocalServer;
		this.botCount = botCount;

		hostEdit = new JTextField(host);
                tempHostName = hostEdit.getText();
		portEdit = new JTextField("" + port);
		nameEdit = new JTextField(name);
		botCountComboBox = new JComboBox(botCountStrings);
		botCountComboBox.setSelectedItem("" + botCount);
		hostLabel = new JLabel("Host: ");
		portLabel = new JLabel("Port: ");
		nameLabel = new JLabel("Name: ");
		botCountLabel = new JLabel("# of bots: ");
		connectBtn = new JButton("Connect");

		// ------------------------------------------------
		// ADDED by Jay S. on July 20
		tokenLabel = new JLabel(icon);
		tokenList = new JComboBox(tokenStrings);

		// Set up the picture.
		tokenLabel.setFont(tokenLabel.getFont().deriveFont(Font.ITALIC));
		tokenLabel.setHorizontalAlignment(JLabel.CENTER);
		updateLabel(tokenStrings[tokenList.getSelectedIndex()]);
		tokenLabel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
		// ------------------------------------------------

		aiCheckBox = new JCheckBox("Enable AI", startAi);
		botCountComboBox.setEnabled(startAi);
		botCountLabel.setEnabled(startAi);
		localServerCheckBox = new JCheckBox("Start local server",
				startLocalServer);
		mainpanel = new JPanel();
		mainpanel.setBorder(BorderFactory.createTitledBorder("Settings"));

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		Container pane = getContentPane();
		GridBagConstraints c = new GridBagConstraints();

		pane.setLayout(new GridBagLayout());
		c.ipadx = 3;
		c.ipady = 3;
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(3, 3, 3, 3);

		c.gridx = 0;
		c.gridy = 0;
		c.ipadx = 0;
		pane.add(hostLabel, c);

		++c.gridx;
		c.ipadx = 100;
		pane.add(hostEdit, c);
                if (startLocalServer)
                {
                    hostEdit.setText("localhost");
                    hostEdit.setEnabled(false);
                }
                     

		++c.gridx;
		c.ipadx = 0;
		pane.add(portLabel, c);

		++c.gridx;
		c.ipadx = 100;
		pane.add(portEdit, c);

		c.gridx = 0;
		++c.gridy;
		c.ipadx = 0;
		pane.add(nameLabel, c);

		++c.gridx;
		c.ipadx = 100;
		pane.add(nameEdit, c);

		c.gridx = 1;
		++c.gridy;
		c.ipadx = 0;
		pane.add(aiCheckBox, c);

		c.gridx = 3;
		pane.add(localServerCheckBox, c);
                
                botCountLabel.setVisible(true);
		c.gridx = 0;
		++c.gridy;
		pane.add(botCountLabel, c);

                botCountComboBox.setVisible(true);    
		c.gridx = 1;
		pane.add(botCountComboBox, c);
                
                aiCheckBox.addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e)
                    {
                        if(aiCheckBox.isSelected()) {
                            botCountComboBox.setEnabled(true);
			    botCountLabel.setEnabled(true);
			}
                        else {
                            botCountComboBox.setEnabled(false);
			    botCountLabel.setEnabled(false);
			}
                    };
                }   );        
                
                localServerCheckBox.addActionListener(new ActionListener()
                {
                    
                    public void actionPerformed(ActionEvent e)
                    {
                        if(localServerCheckBox.isSelected())
                        {
                            tempHostName = hostEdit.getText();
                            hostEdit.setText("localhost");
                            hostEdit.setEnabled(false);
                        }
                        else
                        {
                            hostEdit.setText(tempHostName);
                            hostEdit.setEnabled(true);
                        }
                    }
                });

		// ------------------------------------------------
		// ADDED by Jay S. on July 20
		c.gridx = 1;
		++c.gridy;
		c.ipadx = 0;
		pane.add(tokenLabel, c);

		c.gridx = 3;
		pane.add(tokenList, c);

		tokenList.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				tokenList_changed(e);
			}
                        
		});
		// ------------------------------------------------

		c.gridx = 0;
		++c.gridy;
		c.gridwidth = 4;
		pane.add(connectBtn, c);

		pack();

		/* center on screen */
		setLocationRelativeTo(null);

		connectBtn.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				connect_pressed();
			}
		});

		/* show window */
		setVisible(true);
	}

	// ------------------------------------------------
	// ADDED by Jay S. on July 20
	public void tokenList_changed(ActionEvent e)
	{
		JComboBox cb = (JComboBox) e.getSource();
		tokenName = (String) cb.getSelectedItem();
		updateLabel(tokenName);
	}

	protected void updateLabel(String name)
	{
		icon = new ImageIcon("images/tokens/" + name + ".png");
		tokenLabel.setIcon(icon);
		if (icon != null)
		{
			tokenLabel.setText(name.toUpperCase());
		} else
		{
			tokenLabel.setText("Image not found.");
		}
	}

	// ------------------------------------------------

	public void connect_pressed()
	{
		readOptions();

		if (validOptions())
		{
			if (startLocalServer)
			{
				boolean r = startServer();
				/*
				 * If we fail to start the server return to connection dialog,
				 * and do not start the client
				 */
				if (!r)
					return;
			}
			startClient();
			/* hide connection dialog box. */
			this.setVisible(false);

		} else
			JOptionPane.showMessageDialog(null, "Invalid Options.", "Error",
					JOptionPane.ERROR_MESSAGE);
	}

	public void readOptions()
	{
		this.name = nameEdit.getText();
		this.host = hostEdit.getText();
		this.port = Integer.parseInt(portEdit.getText());
		this.startAi = aiCheckBox.isSelected();
		this.startLocalServer = localServerCheckBox.isSelected();
		this.botCount = Integer.parseInt((String)botCountComboBox.getSelectedItem());
	}

	public boolean validOptions()
	{
		if (host == null || host.length() == 0)
			return false;
		if (name == null || name.length() == 0)
			return false;
		if (botCount < 0 || botCount > 7)
			return false;
		if (port == 0)
			return false;

		return true;
	}
	
	// ONLY FOR LOCAL SERVER!
	public boolean startServer()
	{
		System.out.println("Starting local server...");

		try
		{
			// uses the Monopd class
			Main.monopd.start();
		} 
		catch ( Exception ioe)
		{
			JOptionPane.showMessageDialog(null, "Could not start server.",
					"Error", JOptionPane.ERROR_MESSAGE);
			return false;
		}

		return true;
	}

	public void startClient()
	{
		Main main = null;

		if (startLocalServer)
		{
			host = Main.localhost;
			port = 1234;
		}

		System.out.print("Player name: " + name + "\n" + "Server: " + host
				+ "\n" + "Port: " + port + "\n" + "AI: "
				+ (startAi ? "enabled" : "disabled") + "\n\n");

		try
		{
			main = new Main(host, port, name);
		} catch (Exception e)
		{
			/*
			 * TODO: we should really have each module doing
			 * error checking. For now, just say something went
			 * wrong and bail out.
			 */
			System.err.println("Error starting game client.");
			System.exit(1);
		}
		if (startAi)
		{
			for (int i = 1; i <= botCount; ++i)
			{
				Main AI = null;

				try
				{
					System.out.println("Starting bot " + i);
					AI = new Main(host, port, "Gator_Bot" + i);
					AI.returnHandle().setVisible(false);
					AI.startAi();
				} catch (Exception e)
				{
					/*
					 * TODO: we should really have each module doing
					 * error checking. For now, just say something went
					 * wrong and bail out.
					 */
					System.err.println("Error starting game client.");
					System.exit(1);
				}
			}
		}
	}
        public static String getToken(){ return tokenName; }
        public static String getTokenFile(){ return "images/tokens" + tokenName + ".png"; }
}
